package com.younion.action.consumer.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.younion.action.consumer.AbstractRequestConsumer;
import com.younion.action.interactive.mobile.ApiConstant;
import com.younion.action.interactive.mobile.ResultObject;
import com.younion.business.IFavourableSmsCheckService;
import com.younion.model.FavourableCheckResult;
import com.younion.util.HttpRequestUtils;
import com.younion.util.JsonUtils;
import com.younion.vo.FavourableSmsCheckVO;

public class FavourableCheckCodeConsumer extends AbstractRequestConsumer {
	private IFavourableSmsCheckService favourableSmsCheckService;

	@Override
	public String execute(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		return checkCode(request, response);
	}

	public String checkCode(HttpServletRequest request,
			HttpServletResponse response) {
		String user_token = request.getParameter("user_token");
		String code = request.getParameter("code");
		ResultObject resultObject = new ResultObject();
		FavourableCheckResult result = new FavourableCheckResult();
		try {
			Map paramMap = new HashMap();
			paramMap.put("userToken", user_token);
			List<FavourableSmsCheckVO> favourableSmsCheckVOs = (List<FavourableSmsCheckVO>) favourableSmsCheckService
					.getByMap(paramMap);
			if (favourableSmsCheckVOs != null
					&& !favourableSmsCheckVOs.isEmpty()) {
				FavourableSmsCheckVO favourableSmsCheckVO = favourableSmsCheckVOs
						.get(0);
				if (new Date().getTime()
						- favourableSmsCheckVO.getLastTime().getTime() > 2 * 60 * 1000) {// 2分钟内有效
					resultObject.setStatus(ApiConstant.SUCCESS_STATUS);
					result.setSuccessful("0");
					resultObject.setMsg("您的验证码已经过期，请重新获取后在2分钟内进行验证！");
				} else if (favourableSmsCheckVO.getCode().equals(code)) {
					resultObject.setStatus(ApiConstant.SUCCESS_STATUS);
					result.setSuccessful("1");
					resultObject.setMsg("验证成功!");
				} else {
					resultObject.setStatus(ApiConstant.SUCCESS_STATUS);
					result.setSuccessful("0");
					resultObject.setMsg("验证码不匹配，验证失败!");
				}
			} else {
				resultObject.setStatus(ApiConstant.SUCCESS_STATUS);
				result.setSuccessful("0");
				resultObject.setMsg("验证失败!");
			}
		} catch (Exception e) {
			resultObject.setStatus(ApiConstant.FALSE_STATUS);
			result.setSuccessful("0");
			resultObject.setMsg(ApiConstant.PUBLIC_EXCEPTION);
			e.printStackTrace();
		}
		resultObject.setResult(result);
		HttpRequestUtils.printContent(JsonUtils.parseObj2Json(resultObject),
				response);
		return null;
	}

	public void setFavourableSmsCheckService(
			IFavourableSmsCheckService favourableSmsCheckService) {
		this.favourableSmsCheckService = favourableSmsCheckService;
	}
}
